package org.demo.test.socket.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BIOSocketServer {

	public static void main(String args[]){
		
		ServerSocket server = null;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		try {
			server = new ServerSocket(6666);
			System.out.println("启动服务：" + 6666);
			while(true){
				System.out.println(df.format(new Date())+" 等待客户端响应！" );
				Socket socket =  server.accept();
				System.out.println(df.format(new Date())+" 获得客户端socket响应！" );
				InputStream in = socket.getInputStream();
				OutputStream os = socket.getOutputStream();
				StringBuffer sb = new StringBuffer();
				int maxLen = 13;
				byte[] contextBytes = new byte[maxLen];
				int realLen;
				System.out.println(df.format(new Date())+" 准备读取客户端数据！" );
				while((realLen = in.read(contextBytes,0,maxLen)) != -1){
					System.out.println("开始读取客户端数据！" );
					sb.append(new String(contextBytes));
					contextBytes = new byte[maxLen];
					if(sb.indexOf("#") != -1) break;
				}
				System.out.println(df.format(new Date())+" 客户端信息：" + sb);
				os.write("服务端处理成功!".getBytes());
				os.close();
				in.close();
				socket.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(server != null){
				try {
					server.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
